// ==UserScript==
// @name			Enhanced Gifter
// @description	Gets rid of loot you do not want
// @include   		http://apps.facebook.com/inthemafia/*
// @include   		http://apps.new.facebook.com/inthemafia/*
// @version		10.12.09
// @contributor	Leyline
// ==/UserScript==

GM_registerMenuCommand('EG - Add as recipient', saveRecipient);
window.setInterval(setupPage, 4000);
setupPage();

try
{//update checker by Jarett @ http://userscripts.org/scripts/show/20145
	function updateCheck(forced)
	{
		if ((forced) || (parseInt(GM_getValue('SUC_last_update', '0')) + 86400000 <= (new Date().getTime())))
		{
			try
			{
				GM_xmlhttpRequest(
				{
					method: 'GET',
					url: 'http://userscripts.org/scripts/source/52429.meta.js?'+new Date().getTime(),
					headers: {'Cache-Control': 'no-cache'},
					onload: function(resp)
					{
						var local_version, remote_version, rt, script_name;
						
						rt=resp.responseText;
						GM_setValue('SUC_last_update', new Date().getTime()+'');
						remote_version=parseInt(/@uso:version\s*(.*?)\s*$/m.exec(rt)[1]);
						local_version=parseInt(GM_getValue('SUC_current_version', '-1'));
						if(local_version!=-1)
						{
							script_name = (/@name\s*(.*?)\s*$/m.exec(rt))[1];
							GM_setValue('SUC_target_script_name', script_name);
							if (remote_version > local_version)
							{
								if(confirm('There is an update available for the Greasemonkey script '+script_name+'\nWould you like to go to the install page now?'))
								{
									GM_openInTab('http://userscripts.org/scripts/show/52429');
									GM_setValue('SUC_current_version', remote_version);
								}
							}
							else if (forced)
								alert('No update is available for '+script_name+'.');
						}
						else
							GM_setValue('SUC_current_version', remote_version+'');
					}
				});
			}
			catch (err)
			{
				if (forced)
					alert('An error occurred while checking for updates:\n'+err);
			}
		}
	}
	GM_registerMenuCommand(GM_getValue('SUC_target_script_name', 'EG') + ' - Manual Update Check', function(){updateCheck(true);});
	updateCheck(false);
}
catch(err){}

function setupPage()
{
	if (document.getElementById('app10979261223_gift_send'))
	{
		if (!document.getElementById('leftBox'))
		{
			var sexyElements = document.getElementsByClassName('sexy_button gift_category_button');
			var leftBox = sexyElements[0].parentNode;
			leftBox.id = 'leftBox';
			leftBox.style.width = '160px';
			leftBox.parentNode.parentNode.parentNode.style.height = '700px';
			leftBox.nextSibling.nextSibling.childNodes[1].style.height = '700px';
			sexyElements[2].parentNode.removeChild(sexyElements[2]);
			sexyElements[1].parentNode.removeChild(sexyElements[1]);
			sexyElements[0].parentNode.removeChild(sexyElements[0]);
			var stockDiv = document.createElement('DIV');
			stockDiv.style.width = '160px';
			stockDiv.style.height = '195px';
			stockDiv.appendChild(document.createTextNode('============= '));
			stockDiv.appendChild(document.createTextNode('View:'));
			stockDiv.appendChild(makeSexyButton('Loot', '', viewLoot, '130px'));
			stockDiv.appendChild(makeSexyButton('Collections', '', viewCollections, '130px'));
			stockDiv.appendChild(makeSexyButton('Boosts', '', viewBoosts, '130px'));
			stockDiv.appendChild(makeSexyButton('All Categories', '', viewAll, '130px'));
			stockDiv.appendChild(makeSexyButton('Settings', 'Shows Setting', viewSettings, '130px'));
			leftBox.appendChild(stockDiv);
			var enhancedGifterDiv = document.createElement('DIV');
			enhancedGifterDiv.style.width = '160px';
			enhancedGifterDiv.style.height = '220px';
			var recipientList = document.createElement('SELECT');
			recipientList.style.width = '142px';
			recipientList.style.marginBottom = '4px';
			recipientList.id = 'recipientList';	
			var userNames = eval(GM_getValue('userNames', []));
			var userIDs = eval(GM_getValue('userIDs', []));
			for (var i = 0; i < userNames.length; i++)
			{
				var recipient = document.createElement('OPTION');
				recipient.id = userIDs[i];
				recipient.title = userIDs[i];
				recipient.textContent = userNames[i];
				recipientList.appendChild(recipient);
			}		
			enhancedGifterDiv.appendChild(document.createTextNode('============= '));
			enhancedGifterDiv.appendChild(document.createTextNode('Recipient:'));
			enhancedGifterDiv.appendChild(recipientList);
			enhancedGifterDiv.appendChild(document.createTextNode('============= '));
			enhancedGifterDiv.appendChild(document.createTextNode('Action:'));
			enhancedGifterDiv.appendChild(makeSexyButton('Execute', 'Sends the loot items', executeSendAll, '130px'));
			enhancedGifterDiv.appendChild(makeSexyButton('Execute Category', 'Sends the currently displayed loot items', executeSendCategory, '130px'));
			enhancedGifterDiv.appendChild(makeSexyButton('Execute Single', 'Sends the currently highlighted loot item', executeSendSingle, '130px'));
			enhancedGifterDiv.appendChild(makeSexyButton('Cancel Send', 'Stops Sending', toggleSending, '130px'));
			enhancedGifterDiv.childNodes[2].style.marginRight = '8px';
			leftBox.appendChild(enhancedGifterDiv);
			var logDiv = document.createElement('DIV');
			logDiv.style.width = '160px';
			logDiv.style.height = '280px';
			logDiv.style.overflow = 'auto';
			logDiv.id = 'logDiv';
			leftBox.appendChild(logDiv);
			var settingsDiv = document.createElement('DIV');
			settingsDiv.style.overflow = 'auto';
			settingsDiv.id = 'settings';
			var settingsTable = document.createElement('TABLE');
			settingsDiv.appendChild(settingsTable);
			var settingsTableBody = document.createElement('TBODY');
			settingsTable.appendChild(settingsTableBody);
			settingsTableBody.appendChild(makeTR(document.createTextNode('Manage Recipients')));
			settingsTableBody.appendChild(makeTR(makeSexyButton('Delete Current', 'Delete the currently displayed recipient', deleteRecipient, '130px')));
			settingsTableBody.appendChild(makeTR(makeSexyButton('Default Current', 'Make the currently displayed recipient default', defaultRecipient, '130px')));
			settingsTableBody.appendChild(makeTR(document.createTextNode('Manage Quantities')));
			settingsTableBody.appendChild(makeTR(makeSexyButton('Save Quantities', 'Saves all values in the text boxes', saveKeeps, '130px')));
			var txtDefaultTextValue = document.createElement('INPUT');
			txtDefaultTextValue.style.background = '#000000';
			txtDefaultTextValue.style.color = '#BCD2EA';
			txtDefaultTextValue.style.textAlign = 'right';
			txtDefaultTextValue.size = '2';
			txtDefaultTextValue.value = GM_getValue('defaultTextValue', 'All');
			txtDefaultTextValue.id = 'txtDefaultTextValue';
			settingsTableBody.appendChild(makeTR(txtDefaultTextValue));
			settingsTableBody.appendChild(makeTR(makeSexyButton('Reset Quantities', 'Resets all the text boxes to value in text box and saves', resetKeeps, '130px')));
			settingsTableBody.appendChild(makeTR(document.createTextNode('Sending Method')));
			settingsTableBody.appendChild(makeTR(makeSexyButton('SendMode', 'Will Keep/Send the value in each box', toggleKeepSendQty, '130px')));
			settingsTableBody.appendChild(makeTR(document.createTextNode('Future Settings')));
			settingsTableBody.appendChild(makeTR(document.createTextNode('---height of this box')));
			settingsTableBody.appendChild(makeTR(document.createTextNode('---autogift option')));
			settingsTableBody.appendChild(makeTR(document.createTextNode('---possible log option')));
			settingsTableBody.appendChild(makeTR(document.createTextNode(' ')));
			settingsTableBody.appendChild(makeTR(document.createTextNode('Settings are saved instantly.')));
			settingsTableBody.appendChild(makeTR(document.createTextNode('Click a loot type button on the left to return.')));
			document.getElementById('app10979261223_table_collection').parentNode.appendChild(settingsDiv);
			document.getElementById('btnSendMode').textContent = GM_getValue('sendMode', 'Keep Quantities');
			viewLoot();
			setupQtyInputs();
		}
	}
	else
	{
		checkAddRecipientToProfilePage();
	}
}

function checkAddRecipientToProfilePage()
{
	var allElements = document.getElementsByClassName('tab_content');	
	for (var i = 0; i < allElements.length; i++)
	{
		if (allElements[i].textContent.match('Profile') == 'Profile')
		{
			if (allElements[i].parentNode.parentNode.lastChild.textContent != 'Add as recipient')
			{
				var userID;
				var userName;
				var content = document.getElementById('app10979261223_content_row');
				var anchorElements = content.getElementsByTagName('A');
				for(var j = 0; j < anchorElements.length; j++)
				{
					if(anchorElements[j].innerHTML == 'Profile')
					{
						var match=/[;&]user=(\d+)/.exec(anchorElements[j].href).toString();
						var comma = match.indexOf(',');
						comma++;
						userID = match.substring(comma);
						userName = anchorElements[j].parentNode.textContent.substr(8, anchorElements[j].parentNode.textContent.indexOf(')') - 8);
						var recipientListItem = document.createElement('LI');
						recipientListItem.className = 'tab_off tab_last';
						var recipientDivision = document.createElement('DIV');
						recipientDivision.className = 'tab_content';
						recipientDivision.style.width = '220px';
						var recipientAnchor = document.createElement('A');
						recipientAnchor.textContent = 'Add as recipient';
						recipientAnchor.addEventListener('click', function(event){saveRecipient();}, true);
						var recipientNameBox = document.createElement('INPUT');
						recipientNameBox.style.background = '#000000';
						recipientNameBox.style.color = '#BCD2EA';
						recipientNameBox.size = '30';
						recipientNameBox.className = 'EGtextBox';
						recipientNameBox.title = userID;
						recipientNameBox.id = 'recipientNameBox';
						recipientNameBox.value = userName;
						recipientDivision.appendChild(recipientAnchor);
						recipientDivision.appendChild(recipientNameBox);
						recipientListItem.appendChild(recipientDivision);
						anchorElements[j].parentNode.parentNode.parentNode.appendChild(recipientListItem);
					}
				}
			}
		}
	}
}

function setupQtyInputs() 
{
	var lootTable = document.getElementById('app10979261223_table_loot');
	var boostsTable = document.getElementById('app10979261223_table_expendables');
	var collectionsTable = document.getElementById('app10979261223_table_collection');
	
	var divElements = lootTable.getElementsByTagName('DIV');
	var divElementsB = boostsTable.getElementsByTagName('DIV');
	var divElementsC = collectionsTable.getElementsByTagName('DIV');

	convertOldKeeps();
	var keeps = eval(GM_getValue('keeps', [[]]));
	
	for (var i = 0; i < divElements.length; i++)
	{
		if (/app10979261223_item_box/.test(divElements[i].id))
		{
			makeGiftQtyInput(divElements[i])
		}
	}
	for (var i = 0; i < divElementsB.length; i++)
	{
		if (/app10979261223_item_box/.test(divElementsB[i].id))
		{
			makeGiftQtyInput(divElementsB[i])
		}
	}
	for (var i = 0; i < divElementsC.length; i++)
	{
		if (/app10979261223_item_box/.test(divElementsC[i].id))
		{
			makeGiftQtyInput(divElementsC[i])
		}
	}

	for (var i = 0; i < keeps.length; i++)
	{
		try
		{
			document.getElementById(keeps[i][0]).value = keeps[i][1];
		}
		catch(err)
		{}
	}

	var inputElements = document.getElementsByClassName('EGtextBox');
	var defaultInputValue = document.getElementById('txtDefaultTextValue').value;
	for (var i = 0, j = inputElements.length; i < j; i++)
	{
		if (inputElements[i].value == '')
		{	
			inputElements[i].value = defaultInputValue;
		}
	}	
}

function makeGiftQtyInput(parElement)
{
	parElement.style.height = '150px';
	var egTable = document.createElement('TABLE');
	parElement.appendChild(egTable);
	var egTableBody = document.createElement('TBODY');
	egTable.appendChild(egTableBody);
	var egTR = document.createElement('TR')
	egTableBody.appendChild(egTR);
	var egTDtext = document.createElement('TD');
	egTR.appendChild(egTDtext);
	var textDiv = document.createElement('DIV');
	textDiv.className = 'EGinputText';
	textDiv.textContent = document.getElementById('btnSendMode').textContent.substr(0,4) + ':';
	egTDtext.appendChild(textDiv);
	var egTDtextBox = document.createElement('TD');
	egTR.appendChild(egTDtextBox);
	var newInputBox = document.createElement('INPUT');
	newInputBox.style.background = '#000000';
	newInputBox.style.color = '#BCD2EA';
	newInputBox.style.textAlign = 'right';
	newInputBox.size = '2';
	newInputBox.className = 'EGtextBox';
	//newInputBox.id = title:category:itemID;
	newInputBox.id = trim(parElement.childNodes[1].textContent) + ':' + parElement.id.charAt(24) + ':' + parElement.id.substr(26);
	newInputBox.setAttribute('EGonHand',parElement.childNodes[5].textContent.replace(/[^0-9]/g,''));
	egTDtextBox.appendChild(newInputBox);
}

function makeSexyButton(text, tip, funct, size)
{
	var sexyButton = document.createElement('A');
	sexyButton.textContent = text;
	sexyButton.title = tip;
	sexyButton.className = 'sexy_button gift_category_button';
	sexyButton.addEventListener('click', funct, true);
	sexyButton.style.width = size;
	sexyButton.id = 'btn' + text.replace(/[^a-zA-Z0-9]/g,'');
	return sexyButton;
}

function makeTR(content)
{
	tr = document.createElement('TR');
	td = document.createElement('TD');
	tr.appendChild(td);
	td.appendChild(content);
	return tr;
}

function viewLoot()
{
	document.getElementById('settings').style.display = 'none';
	document.getElementById('app10979261223_table_loot').style.display = 'block';
	document.getElementById('app10979261223_table_collection').style.display = 'none';
	document.getElementById('app10979261223_table_expendables').style.display = 'none';
	document.getElementById('app10979261223_gift_category').value = '1';
}

function viewCollections()
{
	document.getElementById('settings').style.display = 'none';
	document.getElementById('app10979261223_table_loot').style.display = 'none';
	document.getElementById('app10979261223_table_collection').style.display = 'block';
	document.getElementById('app10979261223_table_expendables').style.display = 'none';
	document.getElementById('app10979261223_gift_category').value = '0';
}

function viewBoosts()
{
	document.getElementById('settings').style.display = 'none';
	document.getElementById('app10979261223_table_loot').style.display = 'none';
	document.getElementById('app10979261223_table_collection').style.display = 'none';
	document.getElementById('app10979261223_table_expendables').style.display = 'block';
	document.getElementById('app10979261223_gift_category').value = '2';
}

function viewAll()
{
	document.getElementById('settings').style.display = 'none';
	document.getElementById('app10979261223_table_loot').style.display = 'block';
	document.getElementById('app10979261223_table_collection').style.display = 'block';
	document.getElementById('app10979261223_table_expendables').style.display = 'block';
}

function viewSettings()
{
	document.getElementById('settings').style.display = 'block';
	document.getElementById('app10979261223_table_loot').style.display = 'none';
	document.getElementById('app10979261223_table_collection').style.display = 'none';
	document.getElementById('app10979261223_table_expendables').style.display = 'none';
	document.getElementById('app10979261223_gift_category').value = '1';
}

function toggleKeepSendQty()
{
	var btn = document.getElementById('btnSendMode')
	if (btn.textContent == 'Keep Quantities')
	{
		btn.textContent = 'Send Quantities';
		btn.title = 'Current setting will Send the value in each box';
	}
	else
	{
		btn.textContent = 'Keep Quantities';
		btn.title = 'Current setting will Keep the value in each box';
	}
	var textElements = document.getElementsByClassName('EGinputText');
	for (var i = 0, l = textElements.length; i < l; i++)
	{
		textElements[i].textContent = btn.textContent.substr(0,4) + ':';
	}

	GM_setValue('sendMode', btn.textContent);
}

function toggleSending()
{
	document.getElementById('btnCancelSend').textContent = 'Send Cancelled';
}

function addToSendListQty(elem)
{
	var btn = document.getElementById('btnSendMode')
	if (btn.textContent == 'Keep Quantities') 
	{
		return elem.getAttribute('EGonHand') - elem.value;
	}
	else
	{
		return elem.value
	}
}

function executeSendAll() {executeSend('All');}
function executeSendCategory() {executeSend('Category');}
function executeSendSingle() {executeSend('Single');}

function executeSend(sendType)
{	//This function should replace the 3 other execute type functions if it tests out well.
	//sendType should be a string value matching one of the 3 following strigns. 'All' 'Category' 'Single'
	var sendList = [[]];
	var toSendQty = 0;
	var arrElemID = [];
	var inputElements = document.getElementsByClassName('EGtextBox');
	var category = document.getElementById('app10979261223_gift_category').value;
	
	for (var i = 0, j = inputElements.length; i < j; i++)
	{
		toSendQty = addToSendListQty(inputElements[i]);
		arrElemID = inputElements[i].id.split(':');
		if (
			(toSendQty > 0) &&
				(
				(sendType == 'All')
				||
				((sendType == 'Category') && (arrElemID[1] == category))
				||
				((sendType == 'Single') && (inputElements[i].parentNode.parentNode.parentNode.parentNode.parentNode.style.border == '1px solid rgb(255, 255, 0)'))
				)
		)
		{
			sendList[sendList.length] = arrElemID;
			sendList[sendList.length-1][3] = toSendQty;
		}
	}
	if (sendList.length == 0)
	{
		alert('There is nothing to send');
	}
	else
	{
		setupGiftingFrame(sendList);
		send(sendList);
	}
}

function setupGiftingFrame(sendList)
{
	var logDiv = document.getElementById('logDiv');
	//while (logDiv.hasChildNodes()) {logDiv.removeChild(logDiv.firstChild)}
	
	if (!document.getElementById('giftingFrame')) {
		var giftingFrame = document.createElement('IFRAME');
	  	giftingFrame.id = 'giftingFrame'; 
	  	giftingFrame.style.width = 10+'px'; 
	  	giftingFrame.style.height = 10+'px'; 
	  	logDiv.appendChild(giftingFrame);
	}

	if (!document.getElementById('sentList')) {
		var sentList = document.createElement('DIV');
		sentList.id = 'sentList';
		var sentItem = document.createElement('DIV');
		sentItem.appendChild(document.createTextNode(' '));
		sentList.appendChild(sentItem);	
		logDiv.appendChild(sentList);
	} 
	else
	{
		var sentList = document.getElementById('sentList');
		while (sentList.hasChildNodes()) {sentList.removeChild(sentList.firstChild)}
	}

	var recipientList = document.getElementById('recipientList');
	var userID = recipientList.childNodes[recipientList.selectedIndex].id;
	var userName = recipientList.childNodes[recipientList.selectedIndex].value;

  	document.getElementById('btnCancelSend').textContent = 'Cancel Send';
  	
  	sentList.appendChild(document.createTextNode('Sending to: ' + userName));
  	sentList.appendChild(document.createElement('BR'))
  	for (var i = 0; i < sendList.length; i++)
  	{
	  	sentList.appendChild(document.createTextNode(sendList[i][3] + ' ' + sendList[i][0]));
	  	sentList.appendChild(document.createElement('BR'))
  	}
}

function send(sendList)
{
	var recipientList = document.getElementById('recipientList');
	var userID = recipientList.childNodes[recipientList.selectedIndex].id;
	var userName = recipientList.childNodes[recipientList.selectedIndex].value;
	var giftingFrame = document.getElementById('giftingFrame');
	var sentList = document.getElementById('sentList');
	for (var i = 0, j = sendList.length; i < j; i++)
	{
		if (document.getElementById('btnCancelSend').textContent != 'Cancel Send') {
			sendList.length = 0;
			sentList.appendChild(document.createElement('BR'))
			sentList.appendChild(document.createTextNode('MANUALLY STOPPED.'));
			giftingFrame.src = '';
			break;
		}
		
		if (sendList[i][3] > 0)
		{
			if (sentList.lastChild.textContent.indexOf(sendList[i][0]) == -1)
			{
				sentList.appendChild(document.createElement('BR'));
				sentList.appendChild(document.createTextNode('---- Next Item ----'));
			}
			sentList.appendChild(document.createElement('BR'));
			sentList.appendChild(document.createTextNode(' ' + sendList[i][3] + ' ' + sendList[i][0]));
			sendList[i][3]--;
			GM_log('sending ' + sendList[i][0] + ' to ' + userID);
			giftingFrame.src = 'http://apps.facebook.com/inthemafia/remote/html_server.php?xw_controller=gift&' + 'recipients[0]=' + userID + '&gift_category=' + sendList[i][1] + '&gift_id=' + sendList[i][2] + '&gift_key=' + document.getElementById('app10979261223_gift_key').value + '&xw_action=send';
			window.setTimeout(function() {send(sendList)}, 4000);
			break;
		}
		else
		{			
			if (i == sendList.length - 1)
			{
				sentList.appendChild(document.createElement('BR'))
				sentList.appendChild(document.createTextNode('DONE SENDING.'));
				sentList.appendChild(document.createElement('BR'))
				sentList.appendChild(document.createTextNode('(refresh to see new inventory.)'));
				giftingFrame.src = '';
				//window.setTimeout(refreshGiftingPage, 4000)
			}
		}
	}	
}

function isArray(obj) { 
   if (obj.constructor.toString().indexOf("Array") == -1) 
      return false; 
   else 
      return true; 
}

function convertOldKeeps()
{
	var keeps = eval(GM_getValue('keeps', [[]]));
	if (!isArray(keeps[0]))
	{
		alert('Old version keeps array detected, upgrading.');
		for (var i = 0; i < keeps.length; i++)
		{
			keeps[i] = [keeps[i].substr(0, keeps[i].lastIndexOf(':')), keeps[i].split(':')[3]];
		}
		GM_setValue('keeps', uneval(keeps));
	}
}

function resetKeeps()
{
	var defaultInputValue = document.getElementById('txtDefaultTextValue').value;
	var inputElements = document.getElementsByClassName('EGtextBox');
	var keeps = [[]];
	for (var i = 0, j = inputElements.length; i < j; i++)
	{
		inputElements[i].value = defaultInputValue;
		keeps[keeps.length] = [inputElements[i].id, defaultInputValue];
	}
	GM_setValue('defaultTextValue', defaultInputValue);
	GM_setValue('keeps', uneval(keeps));
	alert('All quantities have been set to ' + defaultInputValue + ' and saved');
}
	
function saveKeeps()
{
	var keeps = eval(GM_getValue('keeps', [[]]));
	var inputElements = document.getElementsByClassName('EGtextBox');
	var saved = false;
	for (var i = 0, j = inputElements.length; i < j; i++)
	{
		saved = false;
		for (var k = 0; k < keeps.length; k++)
		{
			if (keeps[k][0] == inputElements[i].id)
			{
				keeps[k][1] = inputElements[i].value;
				saved = true;
				break;
			}
		}
		if (!saved)
		{
			keeps[keeps.length] = [inputElements[i].id, inputElements[i].value];
		}
	}	
	GM_setValue('keeps', uneval(keeps));
	alert('Quantities have been saved');
}

function saveRecipient()
{
	var inMafia = false;
	var anchorElements = document.getElementsByTagName('A')
	for (var i = 0; i < anchorElements.length; i++)
	{
		if (anchorElements[i].textContent == 'Remove from Mafia')
		{	
			inMafia = true;
		}
	}
	if (inMafia)
	{	
		var recipientNameBox = document.getElementById('recipientNameBox');
		var userNames = eval(GM_getValue('userNames', []));
		var userIDs = eval(GM_getValue('userIDs', []));
		var newSpot = userNames.length;
		var isDuplicate = false;
		for (var i = 0; i < userIDs.length; i++)
		{
			if (recipientNameBox.title == userIDs[i])
			{
				isDuplicate = true;
			}
		}
		if (isDuplicate)
		{
			alert('You have already saved this recipient');
		}
		else
		{
			userNames[newSpot] = recipientNameBox.value;
			userIDs[newSpot] = recipientNameBox.title;
			GM_setValue('userNames', uneval(userNames));
			GM_setValue('userIDs', uneval(userIDs));
			alert('Mafia Name:' + recipientNameBox.value + '\nMafia ID:' + recipientNameBox.title + '\nNow going to the gifting page.');
			window.location.href = 'http://apps.facebook.com/inthemafia/remote/html_server.php?xw_controller=gift&xw_action=view&xw_city=2';
		}
	}
	else
	{
		alert('Mafia is not a member of your family\nThey cannot be added as a recipient');
	}
}

function deleteRecipient()
{
	var recipientList = document.getElementById('recipientList');
	recipientList.remove(recipientList.selectedIndex);
	var userNames = new Array();
	var userIDs = new Array();
	for (var i = 0; i < recipientList.length; i++)
	{
		userNames[i] = recipientList.childNodes[i].value;
		userIDs[i] = recipientList.childNodes[i].id;
	}
	GM_setValue('userNames', uneval(userNames));
	GM_setValue('userIDs', uneval(userIDs));	
}

function defaultRecipient()
{
	var recipientList = document.getElementById('recipientList');
	var userNames = new Array();
	var userIDs = new Array();
	userNames[0] = recipientList.childNodes[recipientList.selectedIndex].value;
	userIDs[0] = recipientList.childNodes[recipientList.selectedIndex].id;
	for (var i = 0; i < recipientList.length; i++)
	{
		if (i == recipientList.selectedIndex)
		{
			continue;
		}
		else
		{
			userNames[userNames.length] = recipientList.childNodes[i].value;
			userIDs[userIDs.length] = recipientList.childNodes[i].id;
		}
	}
	GM_setValue('userNames', uneval(userNames));
	GM_setValue('userIDs', uneval(userIDs));
}

function refreshGiftingPage()
{
	allElements = document.getElementsByTagName('A');
	for (var i = 0; i < allElements.length; i++)
	{
		if (allElements[i].text == 'Gifting')
		{
			clickElement(allElements[i]);
		}
	}
}

function clickElement(elt)
{
	var evt = document.createEvent('MouseEvents');
	evt.initMouseEvent('click', true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
	elt.dispatchEvent(evt);
}

function trim(str)
{
	return str.replace(/^\s+|\s+$/g,'');
}